package com.beecode.enzyme.abrazos.core;

import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.json.JSONArray;
import org.json.JSONObject;

import com.beecode.enzyme.base.core.WorkspaceService;

public class TargetAPI extends WorkspaceService {

	@Override
	public void doService2(HttpServletRequest req, IWorkspace workspace, Map<String, String> args,
			HttpServletResponse resp) {
		PrintWriter writer = null;
		try {
			resp.setHeader("content-type", "application/json");
			writer = resp.getWriter();

			IPath containerLocation = new Path("/workspace");
			String workspacesPath = workspace.getLocation().toOSString();
			List<String> list = TargetCollector.INSTANCE.targetBundles.get(workspace.getLocation());
			JSONArray arr = new JSONArray();
			for (String location : list) {
				String temp = location.substring(workspacesPath.length());
				IPath path = new Path(temp);
				
				containerLocation = containerLocation.append(path);
				
				JSONObject ret = new JSONObject();
				ret.put("containerLocation", containerLocation.toOSString());
				ret.put("osLocation", location);
				arr.put(ret);
			}
			writer.write(arr.toString());
		} catch (Exception e) {
			if (writer != null) {
				resp.setStatus(500);
				JSONObject ret = new JSONObject();
				ret.put("HttpCode", "500");
				ret.put("Severity", "error");
				ret.put("Message", "读取abrazos target bundles失败！");
				ret.put("DetailedMessage", e.getMessage());
				writer.write(ret.toString());
			} else {
				resp.setStatus(503);
			}
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}

	

}
